package com.cmbc.xiaodu;

import com.baidu.dueros.bot.BaseBot;
import com.baidu.dueros.certificate.Certificate;
import com.baidu.dueros.data.request.IntentRequest;
import com.baidu.dueros.data.request.LaunchRequest;
import com.baidu.dueros.data.request.SessionEndedRequest;
import com.baidu.dueros.data.response.OutputSpeech;
import com.baidu.dueros.data.response.Reprompt;
import com.baidu.dueros.data.response.card.ListCard;
import com.baidu.dueros.data.response.card.StandardCard;
import com.baidu.dueros.data.response.card.StandardCardInfo;
import com.baidu.dueros.data.response.card.TextCard;
import com.baidu.dueros.data.response.directive.display.RenderTemplate;
import com.baidu.dueros.data.response.directive.display.templates.*;
import com.baidu.dueros.data.response.directive.dpl.Document;
import com.baidu.dueros.data.response.directive.dpl.RenderDocument;
import com.baidu.dueros.model.Request;
import com.baidu.dueros.model.Response;
import com.baidu.dueros.nlu.Slot;
import com.cmbc.xiaodu.balance.BalanceService;
import com.cmbc.xiaodu.bill.BillService;
import com.fasterxml.jackson.databind.JsonMappingException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class MinShengBot extends BaseBot {

    private BaseService baseService;

    private static Map<String, String> isLoginMap = new HashMap<String, String>();

    /**
     * 重写onInent方法，处理onInent对话事件
     * 此处为针对同一意图的多个槽位进行回复。
     */
    @Override
    protected Response onInent(IntentRequest intentRequest) {
        BaseService baseService;

        if (intentRequest.getIntentName().contains("手机银行")) {

            // 当用户表达 类似于 “打开我的手机银行” 时，触发登录
            return login();

        }else if ("queryAction".equals(intentRequest.getIntentName())) {

            // 多轮查询类
            /* 不需要登录的查询意图 */
            return this.billHandler();
        } else if ("pushAction".equals(intentRequest.getIntentName())) {

            //推送信息pushAction
            return this.newsHandler();
        } else if ("minPermissionAction".equals(intentRequest.getIntentName())) {

            /* 需要登录才能查询的意图 */
            // 在未登录客户端的情况下，先去登录；  如果已登录再去执行意图查询
            if (isLoginMap.containsKey("username") && isLoginMap.get("username") != null) {

                // 如果已登录，去执行具体的意图
                return this.balanceHandler();
            }
            return login();
        } else {
            // 没有听懂用户表达的意思
            retrunBodyTemplate5();
            // 语音输出
            OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "我没听懂您的意思，您可以换个表达方式与我交流");
            Response response = new Response(outputSpeech);
            return response;
        }

    }

    /**
     * 处理用户登录需求
     * TODO 暂定这里涉及账户关联操作  （关联成功后 再次提示用户表述意图）
     */
    public Response login() {
//        if (isLoginMap.containsKey("username") && isLoginMap.get("username") != null) {
//
//        }else {
        this.retrunBodyTemplate4("请扫描二维码", "token", "请扫描二维码进行身份识别", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1597754010878&di=98542547291d28c5ee4820d3ee3c31ae&imgtype=0&src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F01%2F37%2F17%2F96573c3f71ecd2f.jpg");
        OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "请扫描二维码进行身份识别,然后再次表述您的意图");
        Response response = new Response(outputSpeech);
        isLoginMap.put("username", "tom");
        return response;
        //  }
    }

    /**
     * TODO
     * 用来处理银行卡余额意图
     */
    public Response balanceHandler() {
        //baseService = new BalanceService();

        //  if (isLoginMap.containsKey("username") && isLoginMap.get("username") != null) {
        //如果登陆成功，即可查询余额
        if (null != getSlot("queryBalance") && getSlot("queryBalance").contains("余额")) {
            StandardCard standardCard = new StandardCard("账户信息", "您的账户余额为");
            standardCard.addCueWords("我需要转账给张三");
            standardCard.addCueWords("我需要交电话费");
            OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "用户username您好，您的账户余额为1000元");
            Response response = new Response(outputSpeech, standardCard);
            return response;
//            }else if("退出".equals(getSlot("exit"))){
//                isLoginMap.remove("username");
//                this.retrunBodyTemplate4("您已安全退出","token","您已经安全退出账户","");
//                OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "用户username您好，您已经安全退出账户");
//                Response response = new Response(outputSpeech);
//                return response;

        } else if (null != getSlot("isLogin")) {
            this.retrunBodyTemplate4("您已经登陆", "token", "您已通过身份识别，请再次表达您的意图", "");
            OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "username您好，您已通过身份识别，请再次表达您的意图");
            Response response = new Response(outputSpeech);
            return response;
        } else {
            // 没有听懂用户表达的意思
            retrunBodyTemplate5();
            // 语音输出
            OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "我没听懂您的意思，您可以换个表达方式与我交流");
            Response response = new Response(outputSpeech);
            return response;
        }

//        }else {
//            this.retrunBodyTemplate4("请扫描二维码","token","请扫描二维码进行身份识别","https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1597754010878&di=98542547291d28c5ee4820d3ee3c31ae&imgtype=0&src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F01%2F37%2F17%2F96573c3f71ecd2f.jpg");
//            OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "请扫描二维码进行身份识别");
//            Response response = new Response(outputSpeech);
//            isLoginMap.put("username", "tom");
//            return response;
//        }
    }

    /**
     * TODO
     * 用来处理公共信用意图
     *
     * @return
     */
    private Response newsHandler() {
        return null;
    }

    /**
     * 用来处理信用卡账单意图
     *
     * @return
     */
    private Response billHandler() {
        System.err.println("getSlot(\"exchangeRate\")==" + getSlot("exchangeRate"));
        if (getSlot("exchangeRate") != null && getSlot("exchangeRate").contains("汇率")) {
            // if (getSlot("exchangeRate").equals("汇率")) {
            TextCard textCard = new TextCard("今天的汇率是?");
            // 设置会话信息 TODO
            textCard.setContent("今日汇率是6.9");
            textCard.addCueWord("您也可以查询其它指数类信息");
            textCard.addCueWord("比如今日金价");
            textCard.addCueWord("比如今日上证指数");
            OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "今日汇率是6.9");
            // 构造reprompt
            Reprompt reprompt = new Reprompt(outputSpeech);

            Response response = new Response(outputSpeech, textCard, reprompt);
            return response;
        } else if (getSlot("SZIndex") != null && getSlot("SZIndex").equals("上证指数")) {
            TextCard textCard = new TextCard("今天的上证指数为是?");
            // 设置会话信息 TODO
            textCard.setContent("今日上证指数3450");
            textCard.addCueWord("您也可以查询其它指数类信息");
            textCard.addCueWord("比如今日金价");
            textCard.addCueWord("比如今日上证指数");
            OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "今日上证指数3450");
            // 构造reprompt
            Reprompt reprompt = new Reprompt(outputSpeech);
            Response response = new Response(outputSpeech, textCard, reprompt);
            return response;
        } else if (getSlot("goldPrice") != null && getSlot("goldPrice").equals("金价")) {
            TextCard textCard = new TextCard("今天金价为是?");
            // 设置会话信息 TODO
            textCard.setContent("今天金价为每克330元");
            textCard.addCueWord("您也可以查询其它指数类信息");
            textCard.addCueWord("比如今日汇率");
            textCard.addCueWord("比如今日上证指数");
            OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "今天金价为每克330元");
            // 构造reprompt
            Reprompt reprompt = new Reprompt(outputSpeech);
            Response response = new Response(outputSpeech, textCard, reprompt);
            return response;
        } else {
            // 没有听懂用户表达的意思
            retrunBodyTemplate5();
            // 语音输出
            OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "我没听懂您的意思，您可以换个表达方式与我交流");
            Response response = new Response(outputSpeech);
            return response;
        }
//        if (getSlot("userName") == null) {
//            // 询问姓名槽位monthlysalary
//            ask("userName");
//            return this.askUserName();
//        } else if (getSlot("cardNum") == null) {
//            // 询问卡号槽位
//            ask("cardNum");
//            return this.askCardNum();
//        } else {
//            // 具体计算方法
//            return this.computeBill();
//        }
    }

    /**
     * 重写onSessionEnded事件，处理onSessionEnded对话事件
     *
     * @param sessionEndedRequest SessionEndedRequest请求体
     * @see com.baidu.dueros.bot.BaseBot#onSessionEnded(com.baidu.dueros.data.request.SessionEndedRequest)
     */
    @Override
    protected Response onSessionEnded(SessionEndedRequest sessionEndedRequest) {
//        isLoginMap.put("username",null);
        //      isLoginMap.put("username",false);

        isLoginMap.remove("username");
        this.retrunBodyTemplate4("您已安全退出", "token", "您已经安全退出账户", "");

        // 构造TextCard
        TextCard textCard = new TextCard("感谢再次使用民生服务");
        textCard.setAnchorText("setAnchorText");
        textCard.addCueWord("欢迎再次使用");

        // 构造OutputSpeech
        OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "username您好，您已经安全退出账户,欢迎再次使用民生服务");

//        ListCard listCard = new ListCard();
////        StandardCardInfo item1 = new StandardCardInfo("民生智能服务", "民生智能服务");
////        StandardCardInfo item2 = new StandardCardInfo("应用描述", "民生智能服务是基于百度音箱开发，主要以语音交互为主……");
////        listCard.addStandardCardInfo(item1);
////        listCard.addStandardCardInfo(item2);

        // 构造Response
        Response response = new Response(outputSpeech, textCard);

        return response;
    }

    /**
     * 重写onLaunch方法，处理onLaunch对话事件
     *
     * @param launchRequest LaunchRequest请求体
     * @see com.baidu.dueros.bot.BaseBot#onLaunch(com.baidu.dueros.data.request.LaunchRequest)
     */
    @Override
    protected Response onLaunch(LaunchRequest launchRequest) {
        /**
         * 固定模板
         */
        this.retrunBodyTemplate2();
        // 新建返回的语音内容
        OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "欢迎使用民生服务！");
        // 构造返回的Response
        Response response = new Response(outputSpeech);
        return response;
    }

    /** ************************************************* 处理 账单意图 **************************     **/

    /**
     * 将得到的用户名和卡号 信息进行整合，返回最终的账单信息
     *
     * @return
     */
    private Response computeBill() {
        // 获取多轮槽位值：月薪值、城市信息、查询种类
        String userName = getSlot("userName");
        String cardNum = getSlot("cardNum");
        String ret = "用户名" + userName + "卡号" + cardNum + "总支出为：" + 999 + "总收入为：" + 1000;
        TextCard textCard = new TextCard(ret);
        textCard.setAnchorText("setAnchorText");
        textCard.addCueWord("查询成功");

        setSessionAttribute("key_1", "value_1");
        setSessionAttribute("key_2", "value_2");

        OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, ret);
        Reprompt reprompt = new Reprompt(outputSpeech);
        // 主动结束会话
        this.endDialog();
        Response response = new Response(outputSpeech, textCard, reprompt);
        return response;
    }

    /**
     * 用来处理卡号的具体逻辑
     *
     * @return
     */
    private Response askCardNum() {
        TextCard textCard = new TextCard("您的卡号是多少?");
        textCard.setUrl("www:......");
        textCard.setAnchorText("setAnchorText");
        textCard.addCueWord("您的卡号是多少?");

        setSessionAttribute("key_1", "value_1");
        setSessionAttribute("key_2", "value_2");

        OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "您的卡号是多少?");

        Reprompt reprompt = new Reprompt(outputSpeech);

        Response response = new Response(outputSpeech, textCard, reprompt);

        return response;
    }

    /**
     * 处理用户名的具体逻辑
     *
     * @return
     */
    private Response askUserName() {
        TextCard textCard = new TextCard("您的名字叫什么?");
        textCard.setUrl("www:......");
        textCard.setAnchorText("链接文本");
        textCard.addCueWord("您的名字叫什么?");

        // 设置会话信息 TODO
        setSessionAttribute("key_1", "value_1");
        setSessionAttribute("key_2", "value_2");

        OutputSpeech outputSpeech = new OutputSpeech(OutputSpeech.SpeechType.PlainText, "您的名字是什么?");

        // 构造reprompt
        Reprompt reprompt = new Reprompt(outputSpeech);

        Response response = new Response(outputSpeech, textCard, reprompt);

        return response;
    }

    /**
     * 图片模板
     */
    private void retrunBodyTemplate5() {

        // 构造模板BodyTemplate5
        BodyTemplate5 bodyTemplate = new BodyTemplate5();
        bodyTemplate.setTitle("我没听懂您的意思，您可以换个表达方式与我交流");
        bodyTemplate.setBackgroundImageUrl("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3513354604,2490152873&fm=26&gp=0.jpg");
// 也可以链式set设置信息
//        bodyTemplate.addImage("https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg")
//                .addImage("https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg");
// 定义RenderTemplate指令
        RenderTemplate renderTemplate = new RenderTemplate(bodyTemplate);
        this.addDirective(renderTemplate);

    }

    /**
     * 右图左文模板
     */
    private void retrunBodyTemplate4() {

        // 构造模板BodyTemplate4
        BodyTemplate4 bodyTemplate = new BodyTemplate4();
        bodyTemplate.setToken("token");
        bodyTemplate.setTitle("请扫描二维码");
// 可以链式set设置信息
        bodyTemplate.setPlainContent("请扫描右方二维码进行验证")
                .setBackgroundImageUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1597754010878&di=98542547291d28c5ee4820d3ee3c31ae&imgtype=0&src=http%3A%2F%2Fbpic.588ku.com%2Felement_origin_min_pic%2F01%2F37%2F17%2F96573c3f71ecd2f.jpg");
// 定义RenderTemplate指令
        RenderTemplate renderTemplate = new RenderTemplate(bodyTemplate);
        this.addDirective(renderTemplate);

    }

    private void retrunBodyTemplate4(String title, String token, String plainContent, String backgroupImageurl) {
        // 构造模板BodyTemplate4
        BodyTemplate4 bodyTemplate = new BodyTemplate4();
        bodyTemplate.setToken(token);
        bodyTemplate.setTitle(title);
// 可以链式set设置信息
        bodyTemplate.setPlainContent(plainContent)
                .setBackgroundImageUrl(backgroupImageurl);
// 定义RenderTemplate指令
        RenderTemplate renderTemplate = new RenderTemplate(bodyTemplate);
        this.addDirective(renderTemplate);
    }

    /**
     * 左图右文模板
     */
    private void retrunBodyTemplate3() {
// 构造模板BodyTemplate3
        BodyTemplate3 bodyTemplate = new BodyTemplate3();
        bodyTemplate.setToken("token");
        bodyTemplate.setTitle("您已登陆，请选择如下选项");
// 可以链式set设置信息
        bodyTemplate.setPlainContent("拖尔斯泰-理想的书籍是智慧的钥匙")
                .setBackgroundImageUrl("https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg");

// 定义RenderTemplate指令
        RenderTemplate renderTemplate = new RenderTemplate(bodyTemplate);
        this.addDirective(renderTemplate);
    }

    /**
     * 上图下文模版
     */
    private void retrunBodyTemplate2() {
// 构造模板BodyTemplate2
        BodyTemplate2 bodyTemplate = new BodyTemplate2();
        bodyTemplate.setToken("token");
// 可以链式set设置信息
        bodyTemplate.setPlainContent("民生-财务之门开启的钥匙")
                .setBackgroundImageUrl("https://timgsa.baidu.com/timg?" +
                        "image&quality=80&size=b9999_10000&sec=1597753112541&di=354a4da32e5c4164094101df4c6c8a22&" +
                        "imgtype=0&src=http%3A%2F%2Fphotocdn.sohu.com%2F20160316%2Fmp63673655_1458095829991_1_th.jpeg");

        // 定义RenderTemplate指令
        RenderTemplate renderTemplate = new RenderTemplate(bodyTemplate);
        this.addDirective(renderTemplate);
    }

    /**
     * 文本展现模板
     */
    private void retrunBodyTemplate1() {
        // 构造模板BodyTemplate1
        BodyTemplate1 bodyTemplate = new BodyTemplate1();
        bodyTemplate.setToken("token");
        bodyTemplate.setTitle("托尔斯泰的格言");
// 可以链式set设置信息
        bodyTemplate.setPlainContent("拖尔斯泰-理想的书籍是智慧的钥匙")
                .setBackgroundImageUrl("https://skillstore.cdn.bcebos.com/icon/100/c709eed1-c07a-be4a-b242-0b0d8b777041.jpg");
// 定义RenderTemplate指令
        RenderTemplate renderTemplate = new RenderTemplate(bodyTemplate);
        this.addDirective(renderTemplate);

    }

    protected MinShengBot(Request request) throws IOException {
        super(request);
    }

    protected MinShengBot(String request) throws IOException, JsonMappingException {
        super(request);
    }

    protected MinShengBot(Certificate certificate) throws IOException {
        super(certificate);
    }

    protected MinShengBot(HttpServletRequest request) throws IOException, JsonMappingException {
        super(request);
    }
}
